package com.pickerview;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Toast;
import com.pickerview.lib.MapKeyComparator;
import com.pickerview.lib.ScreenInfo;
import com.pickerview.lib.WeekCheckView;
import com.pickerview.lib.WeekCheckView.OnWeekCheckListener;
import com.pickerview.lib.WheelHourMin;
import com.pickerview.lib.WheelOptions;
import com.pickerview.lib.listener.OnOptionsSelectListener;
import com.pickerview.lib.listener.OnTimeComfirmListener;

/**
 * 通用选择器
 * 
 * @author Sai
 * 
 */
public class CommPickPopupWindow extends PopupWindow implements OnClickListener {

  public enum Type {
    TIME_TIME, OPTIONS, CUSTOM
  }// 开始时间-开始时间,其它选项，自定义

  WheelOptions wheelOptions;
  private OnOptionsSelectListener optionsSelectListener;

  private View rootView; // 总的布局
  WheelHourMin wheelTime;
  private View btnSubmit, btnCancel;
  private static final String TAG_SUBMIT = "submit";
  private static final String TAG_CANCEL = "cancel";
  private StringBuilder weekBuilder = new StringBuilder();
  private StringBuilder weekIndexBuilder = new StringBuilder();
  private String weekIndex = "";
  private String weekIndexCopy = "";
  private String week = "";
  private String weekCopy = "";
  private Context context;
  private Type type;

  public CommPickPopupWindow(Context context, Type type) {
    super(context);
    this.context = context;
    this.type = type;
    this.setWidth(LayoutParams.MATCH_PARENT);
    this.setHeight(LayoutParams.WRAP_CONTENT);
    this.setBackgroundDrawable(new BitmapDrawable());// 这样设置才能点击屏幕外dismiss窗口
    this.setOutsideTouchable(true);
    this.setAnimationStyle(R.style.timepopwindow_anim_style);

    LayoutInflater mLayoutInflater = LayoutInflater.from(context);

    // ----时间转轮
    ScreenInfo screenInfo = new ScreenInfo((Activity) context);

    switch (type) {
      case TIME_TIME:
        rootView = mLayoutInflater.inflate(R.layout.pw_time_time, null);
        WeekCheckView weekCheckView = (WeekCheckView) rootView.findViewById(R.id.week_view);
        weekCheckView.setOnWeekCheckListener(myWeekCheckLisnter);
        View timeView = rootView.findViewById(R.id.include_time);
        wheelTime = new WheelHourMin(timeView);
        wheelTime.screenheight = screenInfo.getHeight();
        for (int i = 0; i < WeekCheckView.WEEKS.length; i++) {
          weekBuilder.append(WeekCheckView.WEEKS[i]).append("、");
          if (i == 0) {
            weekIndexBuilder.append(WeekCheckView.WEEKS.length + "").append("|");
            continue;
          }
          weekIndexBuilder.append(i + 1).append("|");
        }
        week = "周" + weekBuilder.toString().substring(0, weekBuilder.toString().lastIndexOf("、"));
        weekCopy = week;
        weekIndex = weekIndexBuilder.toString().substring(0, weekIndexBuilder.toString().lastIndexOf("|"));
        weekIndexCopy = weekIndex;
        break;

      case OPTIONS:
        rootView = mLayoutInflater.inflate(R.layout.pw_options_options, null);
        // ----转轮
        final View optionspicker = rootView.findViewById(R.id.include_options);
        wheelOptions = new WheelOptions(optionspicker);
        wheelOptions.screenheight = screenInfo.getHeight();
        break;
      case CUSTOM:
        break;
    }

    // -----确定和取消按钮
    btnSubmit = rootView.findViewById(R.id.bt_sure);
    btnSubmit.setTag(TAG_SUBMIT);
    btnCancel = rootView.findViewById(R.id.bt_cancle);
    btnCancel.setTag(TAG_CANCEL);
    btnSubmit.setOnClickListener(this);
    btnCancel.setOnClickListener(this);

    setContentView(rootView);
  }

  public void setPicker(List<String> optionsItems) {
    wheelOptions.setPicker(optionsItems, null, null, false);
  }

  public void setPicker(List<String> options1Items, List<List<String>> options2Items, boolean linkage) {
    wheelOptions.setPicker(options1Items, options2Items, null, linkage);
  }

  public void setPicker(List<String> options1Items, List<List<String>> options2Items,
      List<List<List<String>>> options3Items, boolean linkage) {
    wheelOptions.setPicker(options1Items, options2Items, options3Items, linkage);
  }

  /**
   * 设置选中的item位置
   * 
   * @param option1
   */
  public void setSelectOptions(int option1) {
    wheelOptions.setCurrentItems(option1, 0, 0);
  }

  /**
   * 设置选中的item位置
   * 
   * @param option1
   * @param option2
   */
  public void setSelectOptions(int option1, int option2) {
    wheelOptions.setCurrentItems(option1, option2, 0);
  }

  /**
   * 设置选中的item位置
   * 
   * @param option1
   * @param option2
   * @param option3
   */
  public void setSelectOptions(int option1, int option2, int option3) {
    wheelOptions.setCurrentItems(option1, option2, option3);
  }

  /**
   * 设置选项的单位
   * 
   * @param label1
   * @param label2
   */
  public void setLabels(String label1) {
    wheelOptions.setLabels(label1, null, null);
  }

  /**
   * 设置选项的单位
   * 
   * @param label1
   * @param label2
   */
  public void setLabels(String label1, String label2) {
    wheelOptions.setLabels(label1, label2, null);
  }

  /**
   * 设置选项的单位
   * 
   * @param label1
   * @param label2
   * @param label3
   */
  public void setLabels(String label1, String label2, String label3) {
    wheelOptions.setLabels(label1, label2, label3);
  }

  /**
   * 设置时间范围
   * 
   * @param startHourLs
   * @param startMinLs
   * @param endHourLs
   * @param endMinLs
   */
  public void setRangeTime(List<String> startHourLs, List<String> startMinLs, List<String> endHourLs,
      List<String> endMinLs) {
    wheelTime.setTime2TimePicker(startHourLs, startMinLs, endHourLs, endMinLs);
  }

  private OnWeekCheckListener myWeekCheckLisnter = new OnWeekCheckListener() {
    @Override
    public void onWeekCheckListener(Map<Integer, String> map) {
      StringBuilder sbWeek = new StringBuilder();
      StringBuilder sbWeekIndex = new StringBuilder();
      if (!map.isEmpty()) {
        Map<Integer, String> resultMap = MapKeyComparator.sortMapByKey(map);
        for (Map.Entry<Integer, String> entry : resultMap.entrySet()) {
          sbWeek.append(entry.getValue()).append("、");
          if (entry.getKey() == 0) {
            sbWeekIndex.append(WeekCheckView.WEEKS.length + "").append("|");
            continue;
          }
          sbWeekIndex.append(entry.getKey() + "").append("|");
        }
        week = "周" + sbWeek.toString().substring(0, sbWeek.toString().lastIndexOf("、"));
        weekIndex = sbWeekIndex.toString().substring(0, sbWeekIndex.toString().lastIndexOf("|"));
      } else {
        week = weekCopy;
        weekIndex = weekIndexCopy;
      }
    }
  };

  /**
   * 设置是否循环滚动
   * 
   * @param cyclic
   */
  public void setCyclic(boolean cyclic) {
    switch (type) {
      case TIME_TIME:
        wheelTime.setCyclic(cyclic);
        break;
      case OPTIONS:
        wheelOptions.setCyclic(cyclic);
        break;
      case CUSTOM:
        break;
    }
  }

  public void setVisibleItems(int count) {
    switch (type) {
      case TIME_TIME:
        wheelTime.setVisibleItems(count);
        break;
      case OPTIONS:
        wheelOptions.setVisibleItems(count);
        break;
      case CUSTOM:
        break;
    }
  }

  @Override
  public void onClick(View v) {
    String tag = (String) v.getTag();
    if (tag.equals(TAG_CANCEL)) {
      dismiss();
      return;
    } else {
      switch (type) {
        case TIME_TIME:
          initTime();
          break;
        case OPTIONS:
          initOptions();
          break;
        case CUSTOM:
          break;
      }
      return;
    }
  }

  /**
   * 
   */
  private void initOptions() {
    if (optionsSelectListener != null) {
      int[] optionsCurrentItems = wheelOptions.getCurrentItems();
      optionsSelectListener.onOptionsSelect(optionsCurrentItems[0], optionsCurrentItems[1], optionsCurrentItems[2]);
    }
    dismiss();
  }

  /**
   * 
   */
  private void initTime() {
    if (null != onComfirmListener) {
      int startHour = Integer.valueOf(wheelTime.getTimeRange()[0]);
      int startMin = Integer.valueOf(wheelTime.getTimeRange()[1]);
      int endHour = Integer.valueOf(wheelTime.getTimeRange()[2]);
      int endMin = Integer.valueOf(wheelTime.getTimeRange()[3]);

      String time = wheelTime.getTimeRange()[0] + ":" + wheelTime.getTimeRange()[1] + "-" + wheelTime.getTimeRange()[2]
          + ":" + wheelTime.getTimeRange()[3];
      if (startHour > endHour) {
        Toast.makeText(context, "开始时间不能大于结束时间", 0).show();
        return;
      }
      if (startHour == endHour) {
        if (startMin > endMin) {
          Toast.makeText(context, "开始时间不能大于结束时间", 0).show();
          return;
        }
        if (startMin == endMin) {
          Toast.makeText(context, "开始时间和结束时间不能相同", 0).show();
          return;
        }
      }
      onComfirmListener.onTimeConfirm(week, weekIndex.toString(), time);
      dismiss();
    }
  }

  private OnTimeComfirmListener onComfirmListener;

  public void setOnTimeComfirmListener(OnTimeComfirmListener onComfirmListener) {
    this.onComfirmListener = onComfirmListener;
  }

  public void setOnoptionsSelectListener(OnOptionsSelectListener optionsSelectListener) {
    this.optionsSelectListener = optionsSelectListener;
  }
}
